package com.lsh.ofc.worker.task;

import com.alibaba.fastjson.JSON;
import com.dangdang.ddframe.job.api.JobExecutionMultipleShardingContext;
import com.dangdang.ddframe.job.plugin.job.type.simple.AbstractSimpleElasticJob;
import com.lsh.base.common.exception.BusinessException;
import com.lsh.base.common.json.JsonUtils;
import com.lsh.base.trace.id.filter.TraceIdSetter;
import com.lsh.ofc.core.constant.Constants;
import com.lsh.ofc.core.handler.CreateSumSoObdHandler;
import com.lsh.ofc.core.model.DmgSoObdVo;
import com.lsh.ofc.core.redis.RedisTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.MessageFormat;
import java.util.Map;

/**
 * Project Name: lsh-ofc
 *
 * @author fuhao
 * Date: 18/6/19
 * Time: 18/6/19.
 * 北京链商电子商务有限公司
 * Package name:com.lsh.ofc.worker.task.
 * desc:定时任务，汇总sto
 */
@Slf4j
@Component
public class OfcSoObdSumJob extends AbstractSimpleElasticJob {


    @Autowired
    private CreateSumSoObdHandler sumSoObdHandler;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void process(JobExecutionMultipleShardingContext jobContext) {
        TraceIdSetter.set();
        try {
            //具体kafka数据
            Map<String, String> soObdMap = redisTemplate.hgetAll(Constants.OFC_SO_OBD_SUM_KEY);
            if (null == soObdMap || soObdMap.isEmpty()) {
                return;
            }

            for (Map.Entry<String, String> sdEntry : soObdMap.entrySet()) {
                String messageId = sdEntry.getKey();

                String messageStr = sdEntry.getValue();
                log.info("ofcSoObdSumJob [物美 so obd 汇总] messageStr :" + messageStr);
                final DmgSoObdVo dmgSoObdVo = JsonUtils.json2Obj(messageStr, DmgSoObdVo.class);
                log.info("ofcSoObdSumJob [物美 so obd 汇总] messageJson:" + JSON.toJSONString(dmgSoObdVo));

                //插入数据库
                int success = sumSoObdHandler.process(dmgSoObdVo);
                if (success > 0) {
                    log.info("ofcSoObdSumJob [物美 so obd 汇总] 处理成功 messageId {}", messageId);
                    redisTemplate.hdel(Constants.OFC_SO_OBD_SUM_KEY, messageId);
                }else{
                    log.info("ofcSoObdSumJob [物美 so obd 汇总] 处理失败 messageId {}", messageId);
                }
            }
        } catch (BusinessException e) {
            log.error("ofcSoObdSumJob [物美 so obd 汇总] 异常... " + e.getMessage(), e);
        }
    }


    private String getKey(String messageId) {

        return MessageFormat.format(Constants.OFC_SO_SUM_KEY, messageId);
    }


}
